<?php
	class InvoicePdfUtil{
		public static function getInvoicePdf($invno)
        {
            $invoice = Invoice::model()->findByPk($invno);
            $location = Locations::model()->find(array(
                'condition' => 'locno=:locno and custno=:custno',
                'params' => array(
                    'locno' => $invoice->locno,
                    'custno' => $invoice->custno
                    )));
            $customer = Customers::model()->findByPk($invoice->custno);

            $pdf = new InvPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, 'ANSI_A', true, 'UTF-8', false);

            // set document information
            $pdf->SetCreator(PDF_CREATOR);
            $pdf->SetAuthor('QSI');
            $pdf->SetTitle('Invoice #' . $invoice->invoice);
            $pdf->SetSubject('Invoice');
            $pdf->SetKeywords('');

            $pdf->setMyHeaderData($invoice->invoicedate, $invoice->invoice, $invoice->custno);
            $pdf->setInvoiceType($invoice->invoicetype);

            $pdf->setPrintHeader(true);
            // set header and footer fonts
            $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
            $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

            // set default monospaced font
            $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

            //set margins
            $pdf->SetMargins(PDF_MARGIN_LEFT, 60, PDF_MARGIN_RIGHT);
            $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
            $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

            //set auto page breaks
            $pdf->SetAutoPageBreak(TRUE, 10);

            //set image scale factor
            $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

            //set some language-dependent strings
            // $pdf->setLanguageArray($l);
            // ---------------------------------------------------------
            // set font
            $pdf->SetFont('dejavusans', '', 10);

            if ((isset($_REQUEST['soac'])) && ($invoice->invoicetype == Invoice::TYPE_SALES_ORDERS))
            {

                $pdf->letter = true;
                $pdf->AddPage();
                $pdf->writeHTMLCell(150, 0, 16, 58, "&nbsp;<b>$customer->lastname</b>");
                $pdf->writeHTMLCell(150, 0, 17, 62, "<b>$customer->add1</b>");
                if ($customer->add2)
                {
                    $pdf->writeHTMLCell(150, 0, 17, 66, "<b>$customer->add2</b>");
                    $pdf->writeHTMLCell(150, 0, 17, 72, "<b>$customer->city $customer->state $customer->zip </b>");
                }
                else
                {
                    $pdf->writeHTMLCell(150, 0, 17, 66, "<b>$customer->city $customer->state $customer->zip </b>");
                }
                $html = Yii::app()->controller->renderPartial('/pdf/salesorder', array('invoice' => $invoice), true);
                $pdf->writeHTML($html, true, false, true, false, '');
                $salesPerson = Employees::model()->findByPk($invoice->salesperson);
                $html = Yii::app()->controller->renderPartial('/pdf/sosignature', array('salesPerson' => $salesPerson), true);
                $pdf->writeHTML($html, true, false, true, false, '');
            }
            $pdf->AddPage();
            $itemRows = '';
            $subtotal = 0;
            $invoiceItems = InvoiceLedger::model()->findAll((array(
                'condition' => 'invoice=:invoice',
                'params' => array(
                    'invoice' => $invoice->invoice
                )
                    )));
            $taxcode = Taxcodes::model()->findByPk($invoice->taxcode);
            $tax = 0;
            foreach ($invoiceItems as $item)
            {
                $amount = $item->price * $item->qty;
                $description = $item->description;
                if ($invoice->department == '06')
                    $description = $item->partno . ' : ' . $item->description;
                if (!isset($_REQUEST['list']))
                {
                    if (isset($_GET['total']))
                    {
                        $itemRows .= '<tr>
                         <td align="center"  >' . $item->qty . '</td>
                         <td>' . $description . '</td>

                        </tr>';
                    }else
                        $itemRows .= '<tr>
                         <td align="center"  >' . $item->qty . '</td>
                         <td>' . $description . '</td>
                         <td align="right" >' . $item->price . '</td>
                         <td align="right" >' . number_format($amount, 2) . '</td>
                        </tr>';
                }
                else
                {

                    $itemRows .= '<tr>
                         <td align="center"  >' . $item->qty . '</td>
                         <td>' . $description . '</td>
                         <td align="right" > ______</td>
                        </tr>';
                }
            }

            if ($invoice->discounted)
            {
                if (isset($_GET['total']))
                    $itemRows .= '<tr>
                        
                         <td align="center"  >1.00</td>
                         <td  >DISCOUNT: ' . number_format($invoice->discount_amount, 2) . '</td>
                        
                        </tr>';

                else
                    $itemRows .= '<tr>
                         <td align="center"  >1.00</td>
                         <td>DISCOUNT: '.$invoice->discount_percent.'% Memo: '.$invoice->discount_memo.'</td>
                         <td align="right" >' . number_format($invoice->discount_amount, 2) . '</td>
                          <td align="right" >' . number_format($invoice->discount_amount, 2) . '</td>
                        </tr>';
            }

            $html = '
    <table border="0" cellspacing="5" cellpadding="5">
     <tr>
        <td style="background-color: #dddddd;border: 1px double black;" colspan="2">BILL TO
</td>
        <td style="background-color: #dddddd;border: 1px double black;" colspan="2">SERVICE LOCATION</td>
    </tr>
    </table>';


            //writeHTMLCell ($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=false, $reseth=true, $align='', $autopadding=true)
            //  $pdf->writeHTML($html, true, false, true, false, '');
            $pdf->writeHTMLCell(181, 0, 15, 45, $html);
            $pdf->writeHTMLCell(150, 0, 16, 58, "&nbsp;<b>$customer->lastname</b>");
            $modelAddress = $location;
            if($invoice->billloc!=0)
                $modelAddress = $customer;                            
            $pdf->writeHTMLCell(150, 0, 17, 62, "<b>$modelAddress->add1</b>");
            if ($modelAddress->add2)
            {
                $pdf->writeHTMLCell(150, 0, 17, 66, "<b>$modelAddress->add2</b>");
                $pdf->writeHTMLCell(150, 0, 17, 72, "<b>$modelAddress->city $modelAddress->state $modelAddress->zip </b>");
            }
            else
            {
                $pdf->writeHTMLCell(150, 0, 17, 66, "<b>$modelAddress->city $modelAddress->state $modelAddress->zip </b>");
            }
            $pdf->writeHTMLCell(150, 0, 106, 58, "<b>$invoice->shipname</b>");
            $pdf->writeHTMLCell(150, 0, 106, 62, "<b>$invoice->shipaddress1</b>");
            if ($invoice->shipaddress2)
            {
                $pdf->writeHTMLCell(150, 0, 106, 66, "<b>$invoice->shipaddress2</b>");
                $pdf->writeHTMLCell(150, 0, 106, 70, "<b>$invoice->shipCSZ</b>");
            }
            else
            {
                $pdf->writeHTMLCell(150, 0, 106, 66, "<b>$invoice->shipCSZ</b>");
            }
            $termsList = Customers::model()->getTermList();
            $status = $invoice->getQuoteStatusText();
            switch ($invoice->invoicetype)
            {

                case Invoice::TYPE_SALES_ORDERS:
                    $status = JobsStatus::getText($invoice->salesorderstatus);
                    break;
                case Invoice::TYPE_QUOTE:
                    $status = $invoice->getQuoteStatusText();

                    break;
            }
            $label2 = 'STATUS';
            $value2 = $status;
            
            if ($invoice->department == '05')
            {
                $label = 'CONTRACT NO';
                $value = $invoice->agreementno;
            }
            else
            {
                $label = 'JOB NO';
                $value = $invoice->jobnumber;
            }

            if ($invoice->department == '03')
            {
                $label2 = 'DISPATCH';
                $value2 = $invoice->dispatch;
            }
            else
            {
                $label2 = 'SALES ORDER';
                $value2 = $invoice->salesordersorg;
            }
			if($invoice->invoicetype==Invoice::TYPE_CREDIT_MEMO)
			{
				$label2 = 'Org Invoice';
				$value2 = $invoice->invoiceorg;
			}
            switch ($invoice->invoicetype)
            {
                case Invoice::TYPE_INVOICE :


                    $html = '  <br> <br> <br><br>

<table  cellspacing="0" cellpadding="1" border="1">
    <tr>
    <th align="center" style="background-color: #dddddd;border: 1px double black;">' . $label . '</th>
     <th align="center" style="background-color: #dddddd;border: 1px double black;">PURCHASED BY</th>
     <th align="center" style="background-color: #dddddd;border: 1px double black;">PO</th>
     <th align="center" style="background-color: #dddddd;border: 1px double black;">'. $label2 .'</th>
     <th  align="center" style="background-color: #dddddd;border: 1px double black;">TERMS</th>
     <th  align="center" style="background-color: #dddddd;border: 1px double black;">SALES PERSON</th>
    </tr>
    <tr>
         <td align="center"  >' . $value . '</td>
        <td align="center"  >' . $invoice->purchasedby . '</td>
        <td align="center"  >' . $invoice->ponumber . '</td>
         <td align="center"  >' . $value2 . '</td>
        <td align="center"  >' . $termsList[$invoice->slterms] . '</td>
        <td align="center"  >' . Employees::getEmployeeName($invoice->salesperson) . '</td>

    </tr>
</table>
         <br>';
                    if (isset($_GET['total']))
                        $html.=' <br>
<table  cellspacing="0" cellpadding="3" >
<tr>
<th align="center" style="background-color: #dddddd;width:10%;border: 1px double black;">QTY</th>
<th align="center" style="background-color: #dddddd;width:90%;border: 1px double black;">DESCRIPTION</th>
</tr>' . "

$itemRows
</table>

";
                    else
                        $html.=' <br>
<table  cellspacing="0" cellpadding="3" >
<tr>
<th align="center" style="background-color: #dddddd;width:10%;border: 1px double black;">QTY</th>
<th align="center" style="background-color: #dddddd;width:58%;border: 1px double black;">DESCRIPTION</th>
<th align="center" style="background-color: #dddddd;width:17%;border: 1px double black;">PRICE EACH</th>
<th align="center" style="background-color: #dddddd;width:15%;border: 1px double black;">AMOUNT</th>
</tr>' . "

$itemRows
</table>

";
                    break;
                case Invoice::TYPE_SALES_ORDERS:
                    $html = '  <br> <br> <br><br>

<table  cellspacing="0" cellpadding="1" border="1">
    <tr>
    <th align="center" style="background-color: #dddddd;border: 1px double black;">' . $label . '</th>
     <th align="center" style="background-color: #dddddd;border: 1px double black;">PURCHASED BY</th>
     <th align="center" style="background-color: #dddddd;border: 1px double black;">PO</th>
     <th align="center" style="background-color: #dddddd;border: 1px double black;">STATUS</th>
     <th  align="center" style="background-color: #dddddd;border: 1px double black;">TERMS</th>
     <th  align="center" style="background-color: #dddddd;border: 1px double black;">SALES PERSON</th>
    </tr>
    <tr>
         <td align="center"  >' . $value . '</td>
        <td align="center"  >' . $invoice->purchasedby . '</td>
        <td align="center"  >' . $invoice->ponumber . '</td>
         <td align="center"  >' . $status . '</td>
        <td align="center"  >' . $termsList[$invoice->slterms] . '</td>
        <td align="center"  >' . Employees::getEmployeeName($invoice->salesperson) . '</td>

    </tr>
</table>';
                    if (isset($_REQUEST['list']))
                    {
                        $html.=' <br>
<table  cellspacing="0" cellpadding="3" >
<tr>
<th align="center" style="background-color: #dddddd;width:10%;border: 1px double black;">QTY</th>
<th align="center" style="background-color: #dddddd;width:58%;border: 1px double black;">DESCRIPTION</th>
<th align="center" style="background-color: #dddddd;width:32%;border: 1px double black;"></th>

</tr>' . "

$itemRows
</table>

";
                    }
                    else if (isset($_GET['total']))
                        $html.=' <br>
<table  cellspacing="0" cellpadding="3" >
<tr>
<th align="center" style="background-color: #dddddd;width:10%;border: 1px double black;">QTY</th>
<th align="center" style="background-color: #dddddd;width:90%;border: 1px double black;">DESCRIPTION</th>
</tr>' . "

$itemRows
</table>

";
                    else
                        $html.=' <br>
<table  cellspacing="0" cellpadding="3" >
<tr>
<th align="center" style="background-color: #dddddd;width:10%;border: 1px double black;">QTY</th>
<th align="center" style="background-color: #dddddd;width:58%;border: 1px double black;">DESCRIPTION</th>
<th align="center" style="background-color: #dddddd;width:17%;border: 1px double black;">PRICE EACH</th>
<th align="center" style="background-color: #dddddd;width:15%;border: 1px double black;">AMOUNT</th>
</tr>' . "

$itemRows
</table>

";
                    break;
                default:
                    $html = '  <br> <br> <br><br>

<table  cellspacing="0" cellpadding="1" border="1">
    <tr>
    <th align="center" style="background-color: #dddddd;border: 1px double black;">' . $label . '</th>
     <th align="center" style="background-color: #dddddd;border: 1px double black;">PURCHASED BY</th>
     <th align="center" style="background-color: #dddddd;border: 1px double black;">PO</th>
     <th align="center" style="background-color: #dddddd;border: 1px double black;">' . $label2 . '</th>
     <th  align="center" style="background-color: #dddddd;border: 1px double black;">TERMS</th>
     <th  align="center" style="background-color: #dddddd;border: 1px double black;">SALES PERSON</th>
    </tr>
    <tr>
         <td align="center"  >' . $value . '</td>
        <td align="center"  >' . $invoice->purchasedby . '</td>
        <td align="center"  >' . $invoice->ponumber . '</td>
         <td align="center"  >' . $value2 . '</td>
        <td align="center"  >' . $termsList[$invoice->slterms] . '</td>
        <td align="center"  >' . Employees::getEmployeeName($invoice->salesperson) . '</td>

    </tr>
</table>';

                    if (isset($_GET['total']))
                        $html.=' <br>
<table  cellspacing="0" cellpadding="3" >
<tr>
<th align="center" style="background-color: #dddddd;width:10%;border: 1px double black;">QTY</th>
<th align="center" style="background-color: #dddddd;width:90%;border: 1px double black;">DESCRIPTION</th>
</tr>' . "

$itemRows
</table>

";
                    else
                        $html.=' <br>
<table  cellspacing="0" cellpadding="3" >
<tr>
<th align="center" style="background-color: #dddddd;width:10%;border: 1px double black;">QTY</th>
<th align="center" style="background-color: #dddddd;width:58%;border: 1px double black;">DESCRIPTION</th>
<th align="center" style="background-color: #dddddd;width:17%;border: 1px double black;">PRICE EACH</th>
<th align="center" style="background-color: #dddddd;width:15%;border: 1px double black;">AMOUNT</th>
</tr>' . "

$itemRows
</table>

";
            }
            //  echo $html;
            $pdf->writeHTML($html, true, false, true, false, '');
            if (!isset($_REQUEST['list']))
            {
                $appPaymentsInfoHtml = "<b>Applied Payments</b>";
                $balanceOwnedInfoHtml = "<b>Balance Owed</b>";

                $subtotalInfoHtml = "<b>Subtotal: </b>";
                $taxInfoHtml = "<b>Tax:</b>";
                $totalInfoHtml = "<b>Total:</b>";


                if ($invoice->invoicetype == Invoice::TYPE_INVOICE)
                {
                    $appPayments = $invoice->getPaymentApplied();
                    $balanceOwned = $invoice->getBalanceDue();
                }
                else if ($invoice->invoicetype == Invoice::TYPE_SALES_ORDERS)
                {
                    $appPayments = $invoice->getPaymentApplied();
                    $balanceOwned = $invoice->getBalanceDue();
                }
                else
                {
                    $appPayments = $balanceOwned = '0.00';
                }
				$tax = $invoice->amountcharge - $invoice->invoiceamount;
                $tax = number_format($tax-$tax*$invoice->discount_percent/100, 2);
                $subtotalHtml = '<b  style="text-align:right;">' . number_format($invoice->invoiceamount-$invoice->discount_amount, 2) . '</b>';
                $taxHtml = '<b  style="text-align:right;">' . $tax . '</b>';
                $totalHtml = '<b  style="text-align:right;">' . number_format($invoice->amountcharge - $invoice->amountcharge*$invoice->discount_percent/100 , 2) . '</b>';
                $appPaymentsHtml = '<b  style="text-align:right;">' . number_format($appPayments, 2) . '</b>';
                $balanceOwnedHtml = '<b  style="text-align:right;">' . number_format($balanceOwned, 2) . '</b>';
                /* Total info */
				$currentHeight = $pdf->GetY();
				$check_pagebreak = $pdf->checkPageBreakHeight(18,$currentHeight,false);
				if($check_pagebreak)
				{
					$pdf->AddPage();
					$pdf->lastPage();
					$currentHeight = $pdf->GetY();
					$currentHeight -=40;
					$pdf->writeHTMLCell(25, 0, 33, $currentHeight+44, $subtotalInfoHtml);
					$pdf->writeHTMLCell(25, 0, 33, $currentHeight+48, $taxInfoHtml);
					$pdf->writeHTMLCell(25, 0, 33, $currentHeight+52, $totalInfoHtml);
					$pdf->writeHTMLCell(25, 0, 170, $currentHeight+44, $subtotalHtml);
					$pdf->writeHTMLCell(25, 0, 170, $currentHeight+48, $taxHtml);
					$pdf->writeHTMLCell(25, 0, 170, $currentHeight+52, $totalHtml);

					$pdf->writeHTMLCell(50, 0, 33, $currentHeight+56, $appPaymentsInfoHtml);
					$pdf->writeHTMLCell(50, 0, 33, $currentHeight+62, $balanceOwnedInfoHtml);

					$pdf->writeHTMLCell(25, 0, 170, $currentHeight+56, $appPaymentsHtml);
					$pdf->writeHTMLCell(25, 0, 170, $currentHeight+62, $balanceOwnedHtml);
				}
				else
				{
					$pdf->writeHTMLCell(25, 0, 33, 244, $subtotalInfoHtml);
					$pdf->writeHTMLCell(25, 0, 33, 248, $taxInfoHtml);
					$pdf->writeHTMLCell(25, 0, 33, 252, $totalInfoHtml);
					$pdf->writeHTMLCell(25, 0, 170, 244, $subtotalHtml);
					$pdf->writeHTMLCell(25, 0, 170, 248, $taxHtml);
					$pdf->writeHTMLCell(25, 0, 170, 252, $totalHtml);

					$pdf->writeHTMLCell(50, 0, 33, 256, $appPaymentsInfoHtml);
					$pdf->writeHTMLCell(50, 0, 33, 262, $balanceOwnedInfoHtml);

					$pdf->writeHTMLCell(25, 0, 170, 256, $appPaymentsHtml);
					$pdf->writeHTMLCell(25, 0, 170, 262, $balanceOwnedHtml);
				}
            }
            // set color for background
            $pdf->SetFillColor(255, 255, 215);

            // set font
            $pdf->SetFont('helvetica', '', 8);


            // reset pointer to the last page
            $pdf->lastPage();

            //echo $html;
            // reset pointer to the last page
            $pdf->lastPage();

            return $pdf;
        }
	}


